//
//  FindPasswordViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-6-30.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "FindPasswordViewController.h"
#import "LoginViewController.h"
#import "ResetPasswordViewController.h"
#import "JKCountDownButton.h"
#import <SMS_SDK/SMS_SDK.h>
#import <SMS_SDK/CountryAndAreaCode.h>

@interface FindPasswordViewController ()

@property (weak, nonatomic) IBOutlet UITextField *phoneTxt;
@property (weak, nonatomic) IBOutlet UITextField *yanzm;
@end

@implementation FindPasswordViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    self.title = @"找回密码";
    
    [super viewWillAppear:animated];
}

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}


- (IBAction)backToPre:(id)sender {
//    LoginViewController *findVC = (LoginViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
////    [self.navigationController pushViewController:findVC animated:YES];
//    CATransition* transition = [CATransition animation];
//    transition.duration = 0.5;
//    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
//    transition.type = kCATransitionPush; //kCATransitionMoveIn; //, kCATransitionPush, kCATransitionReveal, kCATransitionFade
//    transition.subtype = kCATransitionFromLeft; //kCATransitionFromLeft, kCATransitionFromRight, kCATransitionFromTop, kCATransitionFromBottom
//    [self.navigationController.view.layer addAnimation:transition forKey:nil];
//    [self.navigationController pushViewController:findVC animated:NO];
    [self.navigationController popViewControllerAnimated:YES];
}

//- (IBAction)next:(id)sender {
//    ResetPasswordViewController *findVC = (ResetPasswordViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ResetPassword"];
//    [self.navigationController pushViewController:findVC animated:YES];
//}


- (IBAction)countDownXibTouched:(JKCountDownButton*)sender {
    BOOL isMatch = [self validateMobile:self.phoneTxt.text];
    if(!isMatch){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请输入正确的手机号"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    [SMS_SDK getVerificationCodeBySMSWithPhone:self.phoneTxt.text
                                          zone:@"86"
                                        result:^(SMS_SDKError *error)
     {
         if (!error)
         {
             //                         [self presentViewController:verify animated:YES completion:^{
             //                             ;
             //                         }];
         }
         else
         {
             UIAlertView* alert=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"codesenderrtitle", nil)
                                                           message:[NSString stringWithFormat:@"状态码：%zi ,错误描述：%@",error.errorCode,error.errorDescription]
                                                          delegate:self
                                                 cancelButtonTitle:NSLocalizedString(@"sure", nil)
                                                 otherButtonTitles:nil, nil];
             [alert show];
         }
         
     }];
    
    
    
    sender.enabled = NO;
    //button type要 设置成custom 否则会闪动
    [sender startWithSecond:60];
    
    [sender didChange:^NSString *(JKCountDownButton *countDownButton,int second) {
        NSString *title = [NSString stringWithFormat:@"剩余%d秒",second];
        return title;
    }];
    [sender didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
        countDownButton.enabled = YES;
        return @"重新获取";
        
    }];
}


- (IBAction)next:(id)sender {
    if(self.phoneTxt.text == nil || [self.phoneTxt.text  isEqual: @""]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请填写手机号"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
        
    } else if(self.yanzm.text == nil || [self.yanzm.text  isEqual: @""]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"请填写短信验证码"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
        
    } else {
        if (self.networkManager == nil) {
            self.networkManager = [[NetworkManager alloc] init];
        }
        
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               self.yanzm.text,@"yzm",self.phoneTxt.text,@"phone" ,nil];
        [self.HUD show:YES];
        [self.networkManager requestWithMethod:findPwdYzm parameter:param delegate:self];
        
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    //[self endRefresh];
    //self.isRefreshing = NO;
    
    NSLog(@"@@@@@@@@@@@@@@@@getvercode");
    if (methodId == findPwdYzm) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            NSDictionary * vercode = [data objectForKeyOrNil:@"resultinfo"];
            if([result isEqualToString:@"000"]){
                NSLog(@"@@@@@@@@@@@@@@%@",vercode);
                NSInteger status = [[vercode objectForKeyOrNil:@"status"] integerValue];
                NSLog(@"@@@@@@@@@@@@@@%d",status);
                if (status == 200) {
                    ResetPasswordViewController *reportVC = (ResetPasswordViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"ResetPassword"];
                    reportVC.phone = self.phoneTxt.text;
                    [self.navigationController pushViewController:reportVC animated:YES];
                    
                } else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:@"短信验证码输入不正确"
                                                                   delegate:nil
                                                          cancelButtonTitle:@"确定"
                                                          otherButtonTitles:nil];
                    [alert show];
                    
                }
            } else if([result isEqualToString:@"001"]){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"该手机号未注册"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            } else if([result isEqualToString:@"002"]){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"短信验证码输入不正确或失效"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            
            
        }
        
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    //[self.HUD hide:YES];
    //[self endRefresh];
    //self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"数据问题获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}


- (BOOL)validateMobile:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动 ：134、135、136、137、138、139、150、151、152、157、158、159、182、183、184、187、188、147、178、1705
     
     电信：180、189、181、153、133、177
     
     联通：130、131、132、152、155、156、185、186、145、175、1708
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|705|(3[5-9]|5[0127-9]|8[23478]|47|78|)\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186、145、175、1708
     17         */
    NSString * CU = @"^1(708|(3[0-2]|45|75|5[256]|8[56])\\d{8})\\d{7}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181,177
     22         */
    NSString * CT = @"^1((33|77|53|8[019])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
